package easier.fast.settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.datastore.core.Serializer;
import easier.app.x.CommonCode;
import easier.fast.AppSettings;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import kotlin.Unit;
import kotlin.coroutines.Continuation;

public class AppSettingsSerializer implements Serializer< AppSettings > {

    @Override
    public AppSettings getDefaultValue() {

        return AppSettings.newBuilder( AppSettings.getDefaultInstance() )
            .setDeviceID( CommonCode.timedUUID() )
            .build();
    }

    @Nullable
    @Override
    public Object readFrom( @NonNull InputStream inputStream, @NonNull Continuation< ? super AppSettings > continuation ) {

        try {
            return AppSettings.parseFrom( inputStream );
        } catch ( IOException e ) {
            e.printStackTrace();
        }
        return getDefaultValue();
    }

    @Nullable
    @Override
    public Object writeTo( AppSettings settings, @NonNull OutputStream outputStream,
        @NonNull Continuation< ? super Unit > continuation ) {

        try {
            settings.writeTo( outputStream );
        } catch ( IOException e ) {
            e.printStackTrace();
        }

        return settings;
    }
}